package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateTimeUtils;
import com.ruoyi.common.utils.PrintUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.http.HttpTools;
import com.ruoyi.system.domain.UmsCustomer;
import com.ruoyi.system.domain.WhPrintLog;
import com.ruoyi.system.domain.WhPrinterConfig;
import com.ruoyi.system.domain.params.PrintParams;
import com.ruoyi.system.domain.params.StorehousePrintParams;
import com.ruoyi.system.domain.params.WarehousePrintParams;
import com.ruoyi.system.domain.vo.EditOrderInfoVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.PrintService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * @author: 陈平安
 * @date: 2023/3/12 23:56
 * @description: 打印业务接口实现类
 */
@Slf4j
@Service
public class PrintServiceImpl implements PrintService {

    @Resource
    private WhOrderMapper orderMapper;
    @Resource
    private PrintUtils printUtils;
    @Resource
    private RedisCache redisCache;
    @Resource
    private WhPrintLogMapper printLogMapper;
    @Resource
    private UmsCustomerMapper umsCustomerMapper;
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    @Resource
    private WhPrinterConfigMapper printerConfigMapper;

    // 底部广告接口
    private static final String ADVERTISEMENT_URL = "http://zx.1024ymz.cn/advertisement/v1/print";
    // 默认广告内容
    private static final String DEFAULT_BOTTOM = "系统定制:17620108885";
    // 默认单据底部二维码地址
    private static final String DEFAULT_QRCODE_URL = "https://www.baidu.com?orderId=%s";
    // 二维码地址key
    private static final String QRCODE_URL_KEY = "sys_config:order:share:url";

    /**
     * 打印订单
     * @param orderId
     */
    @Override
    public void print(Integer orderId, String createBy, WhPrinterConfig printerConfig) {
        EditOrderInfoVo details = orderMapper.selectEditOrderById(orderId);
        if (details == null) {
            log.error("订单id：{}不存在，打印时间：{}", orderId, DateTimeUtils.formatDateTime(new Date()));
            return;
        }
        // 打印模板数据
        PrintParams printParams = new PrintParams();
        String title = details.getCompany().getCname();
        String cnTitle = title.substring(0, title.indexOf(" "));
        String enTitle = title.substring(title.indexOf(" ") + 1);
        printParams.setTitle(cnTitle);
        printParams.setEnTitle(enTitle);
        printParams.setCompanyAddress(details.getCompany().getAddress());
        printParams.setOrderNo("No." + details.getOrderno().toString());
        printParams.setDate(details.getWarehousingTime());
        printParams.setCustomerCode(details.getCustomerCode());
        printParams.setCustomerName(details.getCustomerName());
        printParams.setGoodsName(details.getGoodsName());
        printParams.setPackageQuantity(details.getPackageNum().toString());
        printParams.setQuantity(details.getTotal().toString());
        printParams.setLocation(details.getArea());
        printParams.setStallAddress(details.getSellerAddress());
        printParams.setStallPhone("***");
        printParams.setPrintDate(DateTimeUtils.formatDate(new Date()));
        UmsCustomer umsCustomer = umsCustomerMapper.selectUmsCustomerByUserId(details.getCustomerId());
        if (umsCustomer != null) {
            if (umsCustomer.getNationality() != null) {
                SysDictData sysDictData = sysDictDataMapper.selectDictDataById(Long.parseLong(umsCustomer.getNationality().toString()));
                if (sysDictData != null) {
                    printParams.setCustomerNationality(sysDictData.getDictLabel());
                }
            }
        }
        // 获取分享二维码地址
        String cacheObject = (String) redisCache.getCacheObject(QRCODE_URL_KEY);
        if (StringUtils.isEmpty(cacheObject)) {
            cacheObject = DEFAULT_QRCODE_URL;
        }
        printParams.setQrCode(String.format(cacheObject, details.getId()));
        // 去获取底部广告
        String bottomStr = getBottomString();
        printParams.setBottom(StringUtils.isEmpty(bottomStr) ? DEFAULT_BOTTOM : bottomStr);
        // 发送打印请求
        Map<String, Object> map = printUtils.printContent(printParams.printContent(printParams), printerConfig.getDeviceCode());
        // 添加打印日志
        WhPrintLog printLog = new WhPrintLog();
        printLog.setOrderId(orderId + "");
        if (MapUtils.isEmpty(map)) {
            printLog.setStatus(3);
            printLog.setPrintId("");
            printLog.setOrderNo(details.getOrderno() + "");
            printLog.setCreateBy(createBy);
            printLog.setCreateTime(new Date());
        }
        else {
            Boolean success = MapUtils.getBoolean(map, "success", false);
            printLog.setStatus(success ? 1 : 3);
            try {
                Map<String,Object> dataMap = (Map<String, Object>) MapUtils.getMap(map,"data");
                if (!MapUtils.isEmpty(dataMap)) {
                    printLog.setPrintId(MapUtils.getString(dataMap,"id",""));
                }
            }catch (Exception e) {
                e.printStackTrace();
                printLog.setPrintId("");
            }
            printLog.setOrderNo(details.getOrderno() + "");
            printLog.setCreateBy(createBy);
            printLog.setCreateTime(new Date());
        }
        printLogMapper.insertWhPrintLog(printLog);
    }

    /**
     * 获取底部广告
     * @return
     */
    public String getBottomString() {
        try {
            String res = HttpTools.get(ADVERTISEMENT_URL);
            if (!StringUtils.isEmpty(res)) {
                Map<String,Object> resMap = JSON.parseObject(res, Map.class);
                if (!MapUtils.isEmpty(resMap) && MapUtils.getInteger(resMap,"code",0).equals(2000)) {
                    Map<String,Object> dataMap = JSON.parseObject(MapUtils.getString(resMap,"data",""),Map.class);
                    if (MapUtils.isNotEmpty(dataMap)) {
                        return MapUtils.getString(dataMap,"contactInformation",DEFAULT_BOTTOM);
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取底部广告发生错误：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 打印仓库订单
     * @param params
     */
    @Override
    public void storehousePrint(StorehousePrintParams params) {
        WhPrinterConfig whPrinterConfig = printerConfigMapper.selectWhPrinterConfigById(params.getPrinterDeviceId());
        if (whPrinterConfig == null) {
            throw new ServiceException("打印机设备不存在");
        }
        WarehousePrintParams printParams = new WarehousePrintParams();
        BeanUtils.copyProperties(params,printParams);
        String bottomStr = getBottomString();
        printParams.setBottom(StringUtils.isEmpty(bottomStr) ? DEFAULT_BOTTOM : bottomStr);
        Map<String, Object> map = printUtils.printContent(
                printParams.printContent(printParams), whPrinterConfig.getDeviceCode());
        Boolean success = MapUtils.getBoolean(map, "success", false);
        if (!success) {
            throw new ServiceException("打印失败");
        }
    }
}
